package com.woniu.service.impl;

import com.ruoyi.framework.manager.AsyncManager;
import com.woniu.dao.EmhancedViewDetailsDao;
import com.woniu.dao.RiskControlDao;
import com.woniu.dao.UserDao;
import com.woniu.entity.*;
import com.woniu.service.EnhancedViewDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;

@Service
public class EnhancedViewDetailsServiceImpl implements EnhancedViewDetailsService {
    @Autowired
    EmhancedViewDetailsDao viewDetailsDao;

    @Resource
    RiskControlDao riskControlDao;

    @Resource
    UserDao userDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ScheduledExecutorService scheduledExecutorService;

    @Override
    public List<EnhancedDataRendering> viewDetails() throws IOException, IllegalAccessException {
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                List<User> all = userDao.findAll();
                redisTemplate.opsForList().leftPush("allUser",all);
            }
        });

        //创建容器，用于存储数据, e.g.: 个人信息 个人信息详情
        List<EnhancedDataRendering> sepSavaRiskInfo = new ArrayList<>();
        //查询风控表，获取所有的分控信息
        List<RiskControl> allRiskControl = riskControlDao.findAllRiskControl();
        //遍历结果集，获取风控id
        for (RiskControl riskControl : allRiskControl) {
            //通过风控信息表，查询对应数据渲染表，进行数据的封装
            sepSavaRiskInfo.add(new EnhancedDataRendering(riskControl.getModelName(),viewDetailsDao.EmhancedViewDetails(riskControl.getId())));
        }

        List<EnhancedViewDetails> viewDetails = sepSavaRiskInfo.get(0).getViewDetails();

        List user1 = redisTemplate.opsForList().range("allUser", 0, 0);
        List<User> o = (List<User>)user1.get(0);

        User target = o.get(0);
        System.out.println(target);

        Field[] fields = target.getClass().getDeclaredFields();

        System.out.println("fields的长度"+fields.length);
        System.out.println("viewDetails的长度"+viewDetails.size());
        for (int i = 0; i < viewDetails.size(); i++) {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().equals(viewDetails.get(i).getField())){
                    viewDetails.get(i).setValue(field.get(target));
                    break;
                }
            }
        }
        System.out.println(sepSavaRiskInfo);

        return sepSavaRiskInfo;
    }
}
